package com.wangijun.yuan.web.api;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.wangijun.yuan.web.base.CommonPage;
import com.wangijun.yuan.web.base.CommonResult;
import com.wangijun.yuan.core.domain.*;
import com.wangijun.yuan.core.model.IdParam;
import com.wangijun.yuan.web.model.dto.*;
import com.wangijun.yuan.web.model.vo.CategoryVO;
import com.wangijun.yuan.web.model.vo.MainArticleVO;
import com.wangijun.yuan.web.model.vo.TagInfoVO;
import com.wangijun.yuan.web.model.vo.TopicInfoVO;
import com.wangijun.yuan.web.service.ArticleService;
import com.wangijun.yuan.web.service.OperateInfoService;
import com.wangijun.yuan.web.service.TagInfoService;
import com.wangijun.yuan.web.service.TopicInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Tag(name = "2-首页接口")
@RestController
@RequiredArgsConstructor
@RequestMapping("/main")
public class MainController {

    private final ArticleService articleService;
    private final TagInfoService tagInfoService;
    private final TopicInfoService topicInfoService;
    private final OperateInfoService operateInfoService;

    @Operation(summary = "文章列表", description = "查询文章列表")
    @PostMapping("/article-list")
    CommonResult<CommonPage<MainArticleVO>> articleList(@RequestBody MainArtQrtParam param) {
        return CommonResult.data(articleService.articleList(param));
    }


    @Operation(summary = "关注推荐文章列表", description = "查询已关注的用户，标签，话题文章列表")
    @PostMapping("/article-follow-list")
    CommonResult<CommonPage<MainArticleVO>> articleFollowList(@RequestBody MainArtFollowQryParam param) {
        return CommonResult.data(articleService.articleFollowList(param));
    }


    @Operation(summary = "文章搜索", description = "分词搜索文章")
    @PostMapping("/search-article")
    CommonResult<CommonPage<MainArticleVO>> searchArticle(@RequestBody @Validated SearchParam param) {
        return CommonResult.data(articleService.query(param));
    }


    @Operation(summary = "分类列表", description = "分类信息列表")
    @GetMapping("/category-list")
    CommonResult<List<CategoryVO>> categoryList() {
        List<Category> list = Db.lambdaQuery(Category.class)
                .orderByAsc(Category::getSort).list();
        Map<Long, List<Article>> countMap = Db.lambdaQuery(Article.class)
                .in(Article::getCategoryId, list.stream().map(Category::getId).toList())
                .select(Article::getCategoryId)
                .list()
                .stream().collect(Collectors.groupingBy(Article::getCategoryId));
        return CommonResult.data(Db.list(Category.class).stream()
                .map(i -> {
                    CategoryVO categoryVO = BeanUtil.copyProperties(i, CategoryVO.class);
                    List<Article> countList = countMap.get(categoryVO.getId());
                    categoryVO.setNum(countList == null ? 0 : countList.size());
                    return categoryVO;
                }).toList());
    }


    @Operation(summary = "标签列表", description = "标签信息列表")
    @GetMapping("/tag-list")
    CommonResult<List<TagInfoVO>> tagList() {
        return CommonResult.data(Db.list(TagInfo.class).stream()
                .map(i -> BeanUtil.copyProperties(i, TagInfoVO.class)).toList());
    }

    @Operation(summary = "标签分页查询列表", description = "标签信息分页查询列表")
    @PostMapping("/tag-qry-list")
    CommonResult<CommonPage<TagInfoVO>> tagQryList(@RequestBody TagListParam param) {
        CommonPage<TagInfoVO> data = tagInfoService.tagQryList(param);
        return CommonResult.data(data);
    }


    @Operation(summary = "标签详情获取", description = "标签信息分页查询列表")
    @PostMapping("/tag-get")
    CommonResult<TagInfoVO> tagGet(@RequestBody IdParam param) {
        return CommonResult.data(tagInfoService.get(param.getId()));
    }

    @Operation(summary = "话题分页查询列表", description = "话题信息分页查询列表")
    @PostMapping("/topic-qry-list")
    CommonResult<CommonPage<TopicInfoVO>> topicQryList(@RequestBody TopicListParam param) {
        CommonPage<TopicInfoVO> data = topicInfoService.topicQryList(param);
        return CommonResult.data(data);
    }

    @Operation(summary = "话题详情获取", description = "话题信息")
    @PostMapping("/topic-get")
    CommonResult<TopicInfo> topicGet(@RequestBody IdParam param) {
        return CommonResult.data(topicInfoService.get(param.getId()));
    }

    public record HotDataVO(
            @Schema(description = "数据ID")
            Long id,
            @Schema(description = "显示内容")
            String content,
            @Schema(description = "热度")
            Integer readNum) {
    }

    @Operation(summary = "文章热榜", description = "热榜文章信息")
    @GetMapping("/hot-article")
    CommonResult<List<HotDataVO>> hotArticle() {
        List<Article> list = Db.lambdaQuery(Article.class)
                .orderByDesc(Article::getReadNum).last("limit 7").list();
        return CommonResult.data(list.stream()
                .map(i -> new HotDataVO(i.getId(), i.getTitle(), i.getReadNum()))
                .collect(Collectors.toList())
        );
    }


    public record HotUserVO(
            @Schema(description = "数据ID")
            Long id,
            @Schema(description = "用户名")
            String username,
            @Schema(description = "个人介绍")
            String summary,
            @Schema(description = "头像")
            String avatar,
            @Schema(description = "热度")
            Integer readNum,
            @Schema(description = "是否关注")
            Boolean followFlag
    ) {
    }

    @Operation(summary = "用户热榜", description = "热榜用户信息")
    @GetMapping("/hot-user")
    CommonResult<List<HotUserVO>> hotUser() {

        List<UserInfo> list = Db.lambdaQuery(UserInfo.class)
                .orderByDesc(UserInfo::getReadNum).last("limit 7").list();
        List<Long> followUserIds = operateInfoService.getFollowUserIds();
        return CommonResult.data(list.stream()
                .map(i -> new HotUserVO(i.getId(), i.getUsername(), i.getSummary(), i.getAvatar(), i.getReadNum(), followUserIds.contains(i.getId())))
                .collect(Collectors.toList())
        );
    }


    @Operation(summary = "话题热榜", description = "热榜话题信息")
    @GetMapping("/hot-topic")
    CommonResult<List<HotDataVO>> hotTopic() {
        List<TopicInfo> list = Db.lambdaQuery(TopicInfo.class)
                .orderByDesc(TopicInfo::getReadNum).last("limit 7").list();
        return CommonResult.data(list.stream()
                .map(i -> new HotDataVO(i.getId(), i.getName(), i.getReadNum()))
                .collect(Collectors.toList())
        );
    }


    @Operation(summary = "标签热榜", description = "热榜标签信息")
    @GetMapping("/hot-tag")
    CommonResult<List<HotDataVO>> hotTag() {
        List<TagInfo> list = Db.lambdaQuery(TagInfo.class)
                .orderByDesc(TagInfo::getReadNum).last("limit 15").list();
        return CommonResult.data(list.stream()
                .map(i -> new HotDataVO(i.getId(), i.getName(), i.getReadNum()))
                .collect(Collectors.toList())
        );
    }
}
